package com.sg.service.base.framework.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sg.common.annotations.BanAuto;
import com.sg.common.dto.FieldInfo;
import com.sg.common.exception.BizException;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.dto.base.framework.req.ImplementSpinLockCheckBaseBatchReq;
import com.sg.dto.base.framework.req.QueryBaseBatchDetailReq;
import com.sg.dto.base.framework.req.QueryBaseBatchListReq;
import com.sg.entity.Batch;
import com.sg.mapper.BatchMapper;
import com.sg.service.base.framework.MBatchService;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ：
 * @version 1.0
 * @since 2022/1/19 15:39
 */
@Service
public class MBatchServiceImpl
        extends ServiceImpl<BatchMapper, Batch>
        implements MBatchService {

    @Autowired
    BatchMapper batchMapper;

    /**
     * 1-1-01查询底层框架服务批次列表[227]
     * gen by moon at 10/23/2022, 2:25:31 PM
     */
    @Trace(operationName = "1-1-01查询底层框架服务批次列表")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Batch> queryBaseBatchList(QueryBaseBatchListReq reqDto) {

        try {
            QueryWrapper<Batch> queryWrapper = new QueryWrapper<>();
            reqDto.setIsValid("FALSE");

            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(Batch.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(Batch.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper, likeList, fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(Batch.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);
            queryWrapper.orderByDesc("operate_time");
            return ((List<Batch>) super.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 1-1-01查询底层框架服务批次详情[44]
     * gen by moon at 10/23/2022, 2:25:30 PM
     */
    @Trace(operationName = "1-1-01查询底层框架服务批次详情")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Batch queryBaseBatchDetail(QueryBaseBatchDetailReq reqDto) {

        try {
            reqDto.setIsValid("FALSE");
            reqDto.setSpaceId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());//CURRENT_SPACEID
            reqDto.setAppId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecAppId());//CURRENT_APPID
            QueryWrapper<Batch> queryWrapper = new QueryWrapper<>();
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, new ArrayList<>());
            queryWrapper.orderByDesc("create_time");
            List<Batch> retList = super.list(queryWrapper);
            if (retList != null && retList.size() > 0) {
                Batch retData = retList.get(0);

                return retData;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 1-1-01删除底层框架服务批次	[43]
     * gen by moon at 10/23/2022, 2:25:30 PM
     */
    @Trace(operationName = "1-1-01删除底层框架服务批次	")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBaseBatch(String batchId) {

        return super.removeById(batchId);
    }

    /**
     * 1-1-01修改底层框架服务批次	[42]
     * gen by moon at 10/23/2022, 2:25:29 PM
     */
    @Trace(operationName = "1-1-01修改底层框架服务批次	")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBaseBatch(Batch batch) {

        return super.updateById(batch);
    }

    /**
     * 1-1-01新增底层框架服务批次[41]
     * gen by moon at 10/23/2022, 2:25:29 PM
     */
    @Trace(operationName = "1-1-01新增底层框架服务批次")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addBaseBatch(Batch batch) {
        batch.setBatchId(CommonFunctionHelper.getUid());//DISTRIBUTED_ID
        batch.setBatchNumber(CommonFunctionHelper.getUid());//AUTO_GENERATE
        batch.setBatchEndTime(CommonFunctionHelper.getFutureTime());//FUTURE_CURRENT_TIME
        batch.setSubjectLifeCycle("EDITING");
        batch.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        batch.setCreateInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        batch.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        batch.setCreateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        batch.setIsArchive("FALSE");
        batch.setIsEditing("TRUE");
        batch.setIsValid("FALSE");
        if (super.save(batch)) {
            return batch.getBatchId();
        } else {
            return "-1";
        }

    }

    /**
     * 1-1-01执行悬停查批次[4362]
     * gen by moon at 9/4/2022, 12:28:25 AM
     */
    @Trace(operationName = "1-1-01执行悬停查批次")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    @BanAuto
    public Batch implementSpinLockCheckBaseBatch(ImplementSpinLockCheckBaseBatchReq reqDto) {
        try {
            long count = 500;
            while (true) {
                if (count == 0) {
                    break;
                }
                reqDto.setIsValid("FALSE");
                QueryWrapper<Batch> queryWrapper = new QueryWrapper<>();
                Map<String, Object> fieldInfoMap = null;
                fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
                CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, new ArrayList<>());
                queryWrapper.orderByDesc("create_time");
                if (super.list(queryWrapper) != null && super.list(queryWrapper).size() > 0) {
                    Batch retData = super.list(queryWrapper).get(0);

                    return retData;
                }
                count--;
                Thread.sleep(10);
            }
            throw new BizException("-1", false);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }

    }
}
